<template>
  <div>
    <!--{{contractId}}-->
    <h1>新增合同</h1>
    <!--<h1>{{ contractId === 'add' ? '新增' : '续签'}}合同</h1>-->
    <el-card shadow="never">
      <p style="margin: 10px 0 30px;font-size: 16px;">
        <span style="color: #f65f2f;border: 3px solid #004e66; margin-right: 10px;"></span>
        基本信息
      </p>
      <el-form
        label-width="100px"
        @submit.native.prevent="save('form')"
        :model="model"
        :rules="rules"
        ref="form"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="合同编号" prop="contractNumber">
              <el-input v-model="model.contractNumber" placeholder="输入内容" size="small"></el-input>
            </el-form-item>
            <el-form-item label="摊位名称">
              <my-select
                ref="mySelectStallName"
                url="api/v1/backend/public/stall"
                :isMultiple="true"
                :queryParamers="{status: 0}"
                @selected="mySelectedStall"
              ></my-select>
            </el-form-item>
            <!-- <el-form-item label="所属区域名称">
              <el-input v-model="model.partitionName"></el-input>
            </el-form-item>-->
            <el-form-item label="签订日期">
              <el-date-picker
                @change="changeSignDate"
                v-model="model.signDate"
                type="date"
                placeholder="选择签订日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="到期时间">
              <el-date-picker
                @change="changeDueTime"
                v-model="model.dueTime"
                type="date"
                placeholder="选择到期时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="选择商户" prop="businessId">
              <my-select
                ref="mySelectBusiness"
                url="api/v2/backend/market/contract/choice_business"
                @selected="mySelectedBusiness"
              ></my-select>
            </el-form-item>
            <el-form-item label="联系人">
              <el-input v-model="model.personInCharge"></el-input>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="model.phone"></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="model.remarks"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同图片" prop="photoUrl">
              <el-upload class="avatar-uploader" ref="photoUrl" style="display: inline-block;"
                         action="https://upload.qiniup.com"
                         :on-remove='handleRemove'
                         :on-success="handleSuccessphotoUrl"
                       
                         
                         :data='uploadToken'
                         :before-upload="beforeUpload"
                         list-type="picture-card"
              >
                <!-- <img v-if="model.photoUrl" :src="model.photoUrl" class="avatar"> -->
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <p style="margin: 50px 0 30px;font-size: 16px;">
          <span style="color: #f65f2f;border: 3px solid #004e66; margin-right: 10px;"></span>
          收费相关
        </p>
        <el-row>
          <el-col :span="12">
            <p style="font-size: 14px;">
              收费项目
              <el-button @click="addpayment" type="primary" size="mini">新增</el-button>
            </p>
            <!-- <el-button @click="addBusiness" class="button" size="small" round>添加商户</el-button> -->
            <el-dialog :visible.sync="dialogVisible" width="45%">
              <!--<p style="font-size: 20px;">新增{{paymentName}}</p>-->

              <el-form :model="tableModel" label-width="110px">
                <el-form-item label="收费项目：" prop="paymentTypeName">
                  <el-select
                    v-model="tableModel.paymentTypeName"
                    @change="changePaymentType"
                    placeholder="请选择"
                    size="small"
                  >
                    <el-option
                      v-for="item in paymentTypeList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="单价：" prop="price">
                  <el-input v-model="tableModel.price" size="small"></el-input>
                </el-form-item>
                <el-form-item label="单位：" prop="unit">
                  <el-input v-model="tableModel.unit" size="small"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">不修改{{paymentName}}项目</el-button>
                <el-button type="primary" @click="saveArray">新增{{paymentName}}项目</el-button>
              </span>
            </el-dialog>
            <el-table v-show="isShow" :data="tableArray" style="width: 85%">
              <el-table-column prop="paymentTypeName" label="收费项目"></el-table-column>
              <el-table-column prop="price" label="单价"></el-table-column>
              <el-table-column prop="unit" label="单位"></el-table-column>
              <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                  <!-- <el-button @click="paymentEdit(scope.row)" type="text" size="small">编辑</el-button> -->
                  <el-button
                    @click.native.prevent="paymentDelete(scope.$index, tableArray)"
                    style="color:#dc1033;"
                    type="text"
                    size="small"
                  >移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>

          <el-col :span="12">
            <p style="font-size: 16px;">
              押金/保证金项目
              <el-button @click="addpressingGold" type="primary" size="mini">新增</el-button>
            </p>

            <el-dialog :visible.sync="pressingDialog" width="45%">
              <p style="font-size: 20px;">新增押金/保证金</p>
              <el-form :model="pressingModel" label-width="120px">
                <el-form-item label="押金项金额(元)：" prop="pressingGoldValue">
                  <el-input v-model="pressingModel.pressingGoldValue"></el-input>
                </el-form-item>
                <el-form-item label="押金项名称：" prop="pressingGoldName">
                  <el-input v-model="pressingModel.pressingGoldName"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="pressingClose">不保存押金项</el-button>
                <el-button type="primary" @click="savePressing">保存押金项</el-button>
              </span>
            </el-dialog>
            <el-table v-show="pressingIsShow" :data="pressingTableArray" style="width: 85%">
              <el-table-column prop="pressingGoldValue" label="押金项金额(元)"></el-table-column>
              <el-table-column prop="pressingGoldName" label="押金项名称"></el-table-column>
              <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                  <el-button
                    @click.native.prevent="pressingDelete(scope.$index, pressingTableArray)"
                    style="color:#dc1033;"
                    type="text"
                    size="small"
                  >移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <el-row style="margin-bottom: 30px;">
          <el-col :span="8" style="color: #fff;">0</el-col>
          <el-col :span="8">
            <el-button
              type="primary"
              native-type="submit('form')"
              style="background: #004e66;margin-top: 50px;"
            >保存</el-button>
          </el-col>
          <el-col :span="8" style="color: #fff;">0</el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import MySelect from "@/components/MySelect";
import { formatDate2 } from "@/utils";

export default {
  data() {
    return {
      disabled: false,
      uploadToken: {
        key: "",
        token: ""
      },

      model: {
        renewContractId: 0, //   续签合同id，新增时为0
        signDate: formatDate2(new Date()), //		string	true	签订日期
        dueTime: "", //		date	true	到期时间
        businessId: 0, //	int	商户id
        businessName: "", //	string	商户名称
        personInCharge: "", // 联系人
        // stallId: 0, //	int	摊位id
        stallIds: "", // string	true	摊位ids	多个英文逗号分隔
        // stallName: '', //	string	摊位名称
        phone: "", //	string	手机号
        // partitionId: '', //	string	区域id
        // partitionName: '', //	string	区域名称
        contractNumber: "", //		string	true	合同编号
        photoUrl: "", //	string	true	合同图片地址
        paymentTypeName: "", // 收费名称

        // 最后要提交的 json 所有新增的收费项目
        payService: [],
        contractPhoto: [], // json	true	合同图片
        // 押金/保证金
        pressingGold: [] //		json	true	押金项
      },

      tableArray: [], // 表格数据
      tableModel: {
        price: 0, //	int	true	单价
        paymentTimeTypeName: formatDate2(new Date()), //	string	true	缴费时间(名称)
        paymentTypeName: "", // 收费名称
        paymentTypeId: "", //	int	true	收费项目基础表id
        unit: "", //	string	true	单位
        paymentTimeType: "", //	string	true	缴费时间(标志)
        timePos: "", //	int	true	计费头尾 0.未设置 1.头 2.尾
        months: "", //	string	true	月份，如：1,4,7,10
        day: "" //	int	true	天
      },

      // 固定收费项目
      paymentTypeList: [], // 收费项目
      isShow: false,
      paymentName: "", // 是什么费用
      paymentTypeDataArray: [], // 数据源 数组
      dialogVisible: false,

      // 编辑
      editDialog: false,

      // 押金/保证金
      //        pressingGold: [], //		json	true	押金项
      pressingModel: {
        pressingGoldName: "", //	string	true	押金项名称
        pressingGoldValue: "" //	string	true	押金项金额
      },
      pressingDialog: false,
      pressingTableArray: [],
      pressingIsShow: false,

      rules: {
        contractNumber: [
          { required: true, message: "请输入合同编号", trigger: "change" }
        ],
        stallName: [
          { required: true, message: "请输入摊位名称", trigger: "change" }
        ]
      }
    };
  },
  components: {
    MySelect
  },
  //    props: {
  //      contractId: {}
  //    },
  watch: {
    "$store.state.app.marketId"(val, oldVal) {
      this.goodsToken();
      this.getPaymentType(this.model.paymentTypeName);
      //        this.contractId !== 'add' && this.fetch(this.contractId)
      let date = new Date();
      let year = date.getFullYear();
      let mon = date.getMonth() + 12;
      let day = date.getDate();
      if (mon > 11) {
        year = year + 1;
        mon = date.getMonth() + 1;
      }
      if (mon < 10) {
        mon = "0" + mon;
      }
      if (day < 10) {
        day = "0" + day;
      }
      this.model.dueTime = year + "-" + mon + "-" + day;
    }
  },
  mounted() {
        //  console.log(this.$route.query.contractId)
    this.goodsToken();
    this.getPaymentType(this.model.paymentTypeName);
    //      this.contractId !== 'add' && this.fetch(this.contractId)
    let date = new Date();
    let year = date.getFullYear();
    let mon = date.getMonth() + 12;
    let day = date.getDate();
    if (mon > 11) {
      year = year + 1;
      mon = date.getMonth() + 1;
    }
    if (mon < 10) {
      mon = "0" + mon;
    }
    if (day < 10) {
      day = "0" + day;
    }
    this.model.dueTime = year + "-" + mon + "-" + day;
  },
  methods: {
    changeSignDate(date) {
      this.model.signDate = formatDate2(date);
    },
    changeDueTime(date) {
      this.model.dueTime = formatDate2(date);
    },

    // 押金/保证金
    addpressingGold() {
      this.pressingDialog = true;
    },
    pressingClose() {
      this.pressingDialog = false;
      this.pressingModel = {};
    },
    savePressing() {
      this.pressingDialog = false;
      this.pressingIsShow = true;

      let temp = JSON.parse(JSON.stringify(this.pressingModel));
      this.pressingTableArray.push(temp);
      this.pressingModel = {};

      let tempArrays = JSON.parse(JSON.stringify(this.pressingTableArray));
      for (var i = 0; i < tempArrays.length; i++) {
        tempArrays[i].price = tempArrays[i].price * 100;
      }

      this.model.pressingGold = JSON.stringify(tempArrays);
    },
    // 移除
    pressingDelete(index, rows) {
      console.log(rows);
      rows.splice(index, 1);
      this.model.pressingGold = JSON.stringify(this.pressingTableArray);
    },

    // 收费项目

    // 数组去重
    unique(arr) {
      return Array.from(new Set(arr));
    },
    // 点击 加号
    addpayment() {
      this.dialogVisible = true;
    },
    // 保存一项一项
    saveArray() {
      this.dialogVisible = false;
      this.isShow = true;
      // console.log('this.tableModel')
      // console.log(this.tableModel)
      let temp = JSON.parse(JSON.stringify(this.tableModel));
      this.tableArray.push(temp);
      console.log("0 新添加的数组数据", this.tableArray);

      let tempArrays = JSON.parse(JSON.stringify(this.tableArray));
      for (var i = 0; i < tempArrays.length; i++) {
        tempArrays[i].price = tempArrays[i].price * 100;
      }
      this.model.payService = JSON.stringify(tempArrays);
    },
    // 取消 一项
    handleClose(done) {
      this.dialogVisible = false;
    },

    // 编辑 表格 收费项目
    paymentEdit(row) {
      console.log(row);
      this.editDialog = true;
    },

    // 删除 表格 收费项目
    paymentDelete(index, rows) {
      rows.splice(index, 1);
      this.model.payService = JSON.stringify(this.tableArray);
    },
    changePaymentType(type) {
      let obj = {};
      obj = this.paymentTypeDataArray.find(item => {
        // 这里的 this.paymentTypeDataArray 就是上面遍历的数据源
        return item.paymentTypeId === type / 1; // 筛选出匹配数据 数据源里的 type 等于 当前选中的 paymentTypeName
      });
      // Object.assign(obj, this.tableModel)
      this.tableModel = JSON.parse(JSON.stringify(obj));
      this.tableModel.price = obj.price / 100;
      this.model.paymentTypeName = obj.paymentTypeName;
    },
    // 获取 收费项目 类型
    getPaymentType(searchName) {
      this.$store
        .dispatch("contract/fetchPaymentType", { searchName })
        .then(data => {
          this.paymentTypeDataArray = data.items;
          let items = [];
          for (let item of data.items) {
            items.push({
              value: item.paymentTypeId + "",
              label: item.paymentTypeName
            });
          }
          this.paymentTypeList = items;
        })
        .catch(err => {
          this.paymentTypeList = [];
        });
    },

    // 选择商户 商户信息
    mySelectedBusiness(obj) {
      this.model.businessId = obj.value;
      this.model.businessName = obj.label;
      this.model.phone = obj.exData.phone;
      this.model.personInCharge = obj.exData.personInCharge;
    },
    // 摊位 自动完成
    mySelectedStall(arr) {
      this.model.stallIds = arr.join(",");
    },

    handleSuccessphotoUrl(res, file, fileList) {
      this.model.photoUrl = "http://cailanzi.image.cailanzi001.com/" + res.key;
      this.model.contractPhoto.push({photoUrl:this.model.photoUrl});
      console.log(this.model.contractPhoto)
      console.log(res, file, fileList)
      // this.model.contractPhoto = JSON.stringify(this.model.contractPhoto);
      // console.log(this.model.contractPhoto)
      // this.$refs.photoUrl.clearFiles();
      //  console.log(this.model.contractPhoto)
    },

    handleRemove(file, fileList) {
      // console.log(fileList)
      // console.log(file, fileList[0]);
      // this.model.contractPhoto = JSON.parse(this.model.contractPhoto);
      this.model.contractPhoto.pop()
      console.log(this.model.contractPhoto)
    },
    beforeUpload(file) {
      const isPNG = file.type === "image/png";
      const isJPEG = file.type === "image/jpeg";
      const isJPG = file.type === "image/jpg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isPNG && !isJPEG && !isJPG) {
        this.$message.error("上传头像图片只能是 jpg、png、jpeg 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
      //将上传的文件名保存成key,把这个key拼接到外链地址
      const date = new Date();
      this.uploadToken.key = `bill${date.getFullYear()}${date.getMonth() +
        1}${date.getDate()}${date.getHours()}${date.getMinutes()}${date.getSeconds()}${Math.floor(
        Math.random() * 100
      )}.${file.type.split("/")[1]}`;
    },
    //获取上传文件时候的token
    goodsToken() {
      this.$store
        .dispatch("purchaseInfo/uptoken", {})
        .then(data => {
          this.uploadToken.token = data.data.uptoken;
        })
        .catch(err => {});
    },

    // 提交先判断下， 新增 还是 续签 合同
    async save(forname) {
       
      this.$refs[forname].validate(valid => {
        if (valid) {
         console.log("1111111",this.model.contractPhoto)
          this.model.contractPhoto = JSON.stringify(this.model.contractPhoto);
          console.log(this.model.contractPhoto)
          //        if(this.contractId === 'add'){
          this.$store
            .dispatch("contract/fetchContractAddSave", this.model)
            .then(data => {
              if (data) {
                this.$router.push("/property/contract");
                this.$message({
                  type: "success",
                  message: "保存成功"
                });
                this.$refs["mySelectBusiness"].clear();
                this.$refs["mySelectStallName"].clear();
              }
            })
            .catch(err => {
              this.$message({
                type: "warning",
                message: "修改未完成"
              });
            });
          //        }else{
          //          this.$store.dispatch("contract/fetchContractAddSave", this.model)
          //        }
        } else {
          this.$message.error("有必填项未填");
          return false;
        }
      });

      //        this.model = {}
    }
    // 如果是续签, 先获取详情, 填入表单里
    /*async fetch(contractId){
        this.$store.dispatch("contract/fetchContractDetails", {contractId}).then(data=>{
          this.model = data
        })
      }*/
  }
  /*create(){
      // 如果有 contractId 再执行这个函数
      this.contractId !== 'add' && this.fetch(this.contractId)
    }*/
};
</script>

<style lang="scss" scoped>
/deep/ .el-input__inner {
  width: 194px;
}
/deep/ .el-upload--picture-card{
  background-color: white;
  border: none;
} 
.button {
  background: #64d9d6;
  color: #fff;
  margin-left: 40px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
  border: 1px dashed #d9d9d9;
}
.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
</style>
